package com.prime.modelo;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.component.UISelectItem;

/**
 *
 * @author stevenziggiz
 */
public class DataBase {

    public DataBase() {
    }
    
    /**
     * validate that MySQL Driver exist and it create the SQL Connection 
     * @return The SQL Connection
     */
    private static Connection getMySQLConnection() {
        try {
            String driver = "org.gjt.mm.mysql.Driver";
            String url = "jdbc:mysql://localhost/cybertron";
            String username = "root";
            String password = "adminadmin";

            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url, username, password);
            return conn;
        } catch (SQLException ex) {
            Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    public static List<UISelectItem> obtenerItemsComboBox(String tableName, String labelName, String valueName){
        List<UISelectItem> selectItems = new ArrayList<UISelectItem>();
        ResultSet rs;
        Statement st;
        Connection connection;
        UISelectItem selectItem;
        try {
            connection = getMySQLConnection();
            st = connection.createStatement();
            rs = st.executeQuery("SELECT "+labelName+","+valueName+" FROM "+tableName+";");
            while (rs.next()) {
                selectItem = new UISelectItem();
                selectItem.setItemLabel(rs.getString(1));
                selectItem.setItemValue(rs.getObject(2));
                selectItems.add(selectItem);
            }
            st.close();
            rs.close();
        } catch (SQLException ex) {
            Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
        }
        return selectItems;
    }
}
